package vn.pyco.prez.tapestry.services.comet;

import java.util.List;

import org.apache.tapestry5.ioc.ObjectLocator;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.services.PropertyShadowBuilder;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.apache.tapestry5.services.HttpServletRequestFilter;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.server.BayeuxServerImpl;
import org.slf4j.Logger;

import vn.pyco.prez.tapestry.services.comet.internal.BayeuxServerSourceImpl;
import vn.pyco.prez.tapestry.services.comet.internal.CometdRequestFilter;
import vn.pyco.prez.tapestry.services.comet.services.PresentationService;
import vn.pyco.prez.tapestry.services.comet.services.RemoteControlService;

public class BayeuxModule {
   public BayeuxServerSource buildBayeuxServerSource(List<BayeuxServerConfigurer> configurers, ObjectLocator locator,
		 Logger logger, RegistryShutdownHub registryShutdownHub) {
      BayeuxServerSourceImpl impl = new BayeuxServerSourceImpl(configurers, locator, logger);
      registryShutdownHub.addRegistryShutdownListener(impl);
      return impl;
   }

   public static void contributeHttpServletRequestHandler(OrderedConfiguration<HttpServletRequestFilter> filters) {
      filters.addInstance("Cometd", CometdRequestFilter.class);
   }

   public BayeuxServer buildBayeuxServer(BayeuxServerSource bayeuxServerSource, PropertyShadowBuilder shadowBuilder) {
      return shadowBuilder.build(bayeuxServerSource, "bayeux", BayeuxServer.class);
   }
   
   public void contributeBayeuxServerSource(OrderedConfiguration<BayeuxServerConfigurer> configurers){
      configurers.add("bayeuxServices", new BayeuxServerConfigurer(){
         public void configure(BayeuxServerImpl bayeuxServerImpl, List<Class<?>> services) {
             services.add(PresentationService.class);
             services.add(RemoteControlService.class);
         }
      });
   }  
}
